<?

function readyPermissions() { return true; }
function permitted() { return true; }

require_once(E.'_lib/_const.php');
require_once(E.'_lib/_lib.php');
require_once(E.'_lib/_db.php');

function save_db($data) {
	if ($f = file_get_contents('dbconfig.php')) {

		$keys = array(); $values = array();
		foreach ($data as $id => $v) {
			$v = addslashes($v);
			$keys[] = "'{".$id."}'";
			$values[] = "'$v'";
		}

		$f = str_replace($keys, $values, $f);

		if (file_put_contents(E.'_lib/_dbconfig.php', $f)) {
			require_once(E.'_lib/_dbconfig.php');
			return false;
		} else
			return "Can't store the database configuration";
			
	} else
		return "Can't read the database configuration file template";
}

function check_db($data) {
	
print "<br>step 2: check_db: $data[DBProto]<br>";	

print_r($data);
	
	switch($data['DBProto']) {
		case 'mysql':

			require_once E.'_lib/_sql.php';
			if ($Link = mysql_connect($data['DBHost'], $data['DBUser'], $data['DBPassword'])) {
				if (@mysql_select_db($data['DBName'], $Link))
					@mysql_query("SET NAMES $data[DBCharset]");
				else 
					return "Can't select db";
			} else 
				return "No db connection";
			
			break;
					
		case 'oci8':

			require_once '_lib/adodb5/adodb.inc.php';
			$GLOBALS['db'] = NewADOConnection($data['DBProto']);
			$GLOBALS['db']->charSet = 'AL32UTF8';
			
			if (!$GLOBALS['db']->PConnect($data['DBHost'], $data['DBUser'], $data['DBPassword'], $data['DBName']))	return 'No db connection';
				
			break;
			
		default:
			return 'Unknown database server type';
	}
	
	if ($check = save_db($data)) return $check;

print "step 3: before create tables";
		
	create_tables();
	load_dumb();
		
	return false;
}

function create_tables() {
	$sql = file_get_contents(DBProto.'.sql');
	
print "sizeof sql: ".sizeof($sql);	
	
	switch(DBProto) {
		case 'mysql':
		
			if (sizeof($q = explode("\n", $sql))) {
				
				$res = array();
				foreach($q as $s) if (($s = trim($s)) && (substr($s, 0, 2) != '--')) $res[] = $s;
				
				$res = explode(';', implode("\n", $res));
				
				foreach($res as $q)	{
print "$q<br>";
					mysql_query($q);
				}
			}
			
			break;
			
		case 'oci8':
			
			$GLOBALS['db']->Execute($sql);
			
			break;
	}
}


function load_dumb($dumb = 'install.sql') {
	$sql = file_get_contents($dumb);

	$tables = array();
	$data = array();
	
	$s = strtok($sql, "\n");
	while ($s) {
		if ($s = trim($s)) {
			if (preg_match('/^INSERT INTO (\w+) \(([^)]+)\) VALUES\((.+)\);$/', $s, $r)) {		// manually detect date in url
				$table = T.$r[1];
				
				if (!in_array($table, $tables)) {	// new table needs to cleanup
					
					switch(DBProto) {
						case 'mysql':
							mysql_query("TRUNCATE TABLE $table");
							break;
							
						case 'oci8':
							$GLOBALS['db']->Execute("TRUNCATE TABLE $table");
							break;
					}
					
					$tables[] = $table;
				}
				
				$keys = array_trim_empty_str(explode(',', $r[2]));
				
				$val = $r[3];
				$values = array();

				while ($val !== '') {
					
					$t = '';
					if ($val{0} == "'") {	// parse string value
						$val = substr($val, 1);

						do {
							if (($pR = strpos($val, "'")) !== false) {
								$t .= substr($val, 0, $pR);
								$val = substr($val, $pR+1);
								
							} else break; // no closing quote O_o
							
							if ($val && ($val{0} == "'")) {
								$t .= "'";
								$val = substr($val, 1);
								continue;	// that was the doubled apos
							} else break;
							
						} while ($val);
						
						$values[] = str_replace('\r\n', "\n", $t);
						$val = ltrim($val);
						

						if ($val && (($val{0} == ',') || ($val{0} == ';')))			// get out comma
							$val = ltrim(substr($val, 1));

					} else {	// parse non-string value
						$pR = strpos($val, ',');
						if ($pR !== false) {		// delimited by comma
							$values[] = rtrim(substr($val, 0, $pR));
							$val = ltrim(substr($val, $pR + 1));
						} else {		// last value
							if (($pR = strpos($val, ')')) !== false) {	// end of statement
								$values[] = rtrim(substr($val, 0, $pR));
								$val = '';
							} else {	// no )
								$values[] = rtrim($val);
								$val = '';
							}
						}
					}	// end of parse single value
				}	
				
				
				$data = array();
				foreach($keys as $k => $v) 
					$data[$v] = $values[$k];

				dataset('db_insert', $table, $data);

			}
			
		}
		
		$s = strtok("\n");
	}
}
